<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/15
 * Time: 10:10
 */

namespace app\index\controller;


use app\common\controller\PayBase;
use app\index\model\ChongzhiList;
use think\Db;
use think\Exception;
use GuzzleHttp\json_encode;

class Payxlb extends PayBase{
    
    private $pay_notifyurl;   //服务端返回地址
    private $pay_callbackurl;  //页面跳转返回地址
    private $tjurl = 'http://www.777pay.cn/Pay_Index.html';   //提交地址
    
    
    public function __construct(){
        parent::__construct();
        header("Content-type: text/html; charset=utf-8");
        $this->pay_applydate = date('Y-m-d H:i:s');
        
        $this->partner = '180898603';
        $this->key = 'qxhte4fyfdhhuikoj4v1bpzagvjmhrg7';
        $this->pay_notifyurl = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/index/Payxlb/server';
        $this->pay_callbackurl = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/index/Payxlb/page';
    }
    
    
    /**
     * 迅联宝
     * @param 用户名 $username
     * @param string $pay_type
     * @param 交易金额 $amount
     * @param number $from
     */
    public function initPay($username = '', $pay_type = '', $amount = -1, $from = 0){

        //接收数据
        $user = cookie('username','');
        $password = cookie('password','');
        $username =  empty($username) ? input('post.username','') : $username;
        $pay_type = empty($pay_type) ? input('post.pay_type','') : $pay_type;
        $amount = -1 == $amount ? input('post.amount',0) : $amount;

        if ($pay_type == 'null' || $pay_type == '') return packJson('', '请选择支付方式', 500);
        $pay_method = Db::name('pay_type_list')
            ->alias("a")
            ->join('__PAY_METHOD__ b','a.method_id=b.id','LEFT')
            ->where(['a.method'=>18,'a.type_value'=>$pay_type])
            ->field('a.type_name,b.name,b.id,b.method,b.money')->find();
        
        $remark = $pay_method['type_name'].'-'.$pay_method['name'];
        //验证用户信息
        
        if(0 == $from ){
            if(!$user || !$username || ($user!=$username)) return packJson('','用户身份验证失败',500);
            $user_info = Db::name('username')->field('id,us_class,swzh,nbzh,je')->where(['username'=>$username,'password'=>$password])->find();
        }else{
            $user_info = Db::name('username')->field('id,us_class,swzh,nbzh,je')->where(['username'=>$username])->find();
        }
        if (!$user_info) return packJson('', '用户身份验证失败', 500);
        if ($user_info['swzh'] == 1) return packJson('', '试玩账号无法充值', 500);
        if ($user_info['nbzh'] == 1) return packJson('', '内部账号不支持线上充值', 500);
        
        //充值防骚扰是否开启，并进行处理
        $harassment = Db::name('xt_czfsr')->field('open,time_xs')->find();
        $now_time = time();
        if ($harassment['open'] > 0) {
            $nowys = $now_time - $harassment['time_xs'] * 60;
            $old_czjl = Db::name('chongzhi_list')->where('username', $username)->where('cztime', '>', $nowys)->value('id');
            if ($old_czjl > 0) {
                return packJson('', "系统充值防骚扰已开启，{$harassment['time_xs']}分钟内只能充值1次！", 500);
            }
        }

        //验证金额
//        if ($amount <= 0) return packJson('', '请输入充值金额', 500);
//        if ($amount < 10) return packJson('', '最低充值金额为十元人民币', 500);
//        if ($amount > 5000) return packJson('', '充值金额超过范围', 500);

        //计算优惠金额
        
        $msje = $msbs = 0;
        $cz_set = Db::name('xt_chongzhi')->field('xscz_je,xscz_zs')->find();
        $user_class = Db::name('us_class')->where('id', $user_info['us_class'])->value('czzsbl');
        $zsje = $amount * $user_class / 100;
        $zsbs = $user_class;
        if ($amount >= $cz_set['xscz_je']) {
            $msje = $amount * $cz_set['xscz_zs'] / 100;
            $msbs = $cz_set['xscz_zs'];
        }
        //充值方案赠送
        $method_money = 0.00;
        if( floatval( $pay_method['money'] ) > 0 ){
            if( 0==intval( $pay_method['method'] ) ){
                //金额
                $method_money = $pay_method['money'];
            }else{
                //比例
                $method_money = floatval($amount) * floatval($pay_method['money']) / 100;
            }
        }
        $method_money = sprintf("%.2f",substr(sprintf("%.3f", $method_money), 0, -2));

        //生成订单号
        $order_sn = 'XLB' . str_pad($user_info['id'], 5, '0', STR_PAD_LEFT) . rand(1111, 9999);
        
        //组装数据
        if( 1==$from ) $this->href_url.="Third";
        $data = array();
        $data['pay_memberid'] = $this->partner;            #商户号
        $data['pay_orderid'] = $order_sn;               #订单号
        $data['pay_amount'] = $amount;                 #金额 (元)
        $data['pay_applydate'] = $this->pay_applydate;           #订单提交时间
        $data['pay_bankcode'] = $pay_type;     #通道编号
        $data['pay_notifyurl'] = $this->pay_notifyurl;     #服务端返回地址
        $data['pay_callbackurl'] = $this->pay_callbackurl;;            #页面跳转返回地址
        $data['pay_md5sign'] = $this->bulidSign($data);
        $data['pay_productname'] ='迅联宝线上支付';
        $data['pay_attach'] = $username;
        if($pay_type != 917 && $pay_type != 920){
            $data['pay_banktype'] = $pay_type;
            $data['pay_bankcode'] = 918;
        }
        //插入充值信息
        $model = new ChongzhiList();
        if($model->setTransRechargeInfo($order_sn,$amount,$username,0,0,1,$remark,$now_time,'迅联宝线上支付','系统自动',get_ip(),0,$pay_type,$zsje,$zsbs,$msje,$msbs,$user_info['us_class'],'',0,$method_money,$user_info['je']) ){
            //跳转支付页
            $url = self::buildForm($data,$this->tjurl);
            return packJson( htmlentities($url) ,'',201);
        }else{
            return packJson('','订单生产错误',500);
        }
    }
    
    
    /**
     * 签名加密
     */
    private function bulidSign($native)
    {
        ksort($native);
        $md5str = '';
        foreach ($native as $key => $val) {
            $md5str = $md5str . $key . "=" . $val . "&";
        }
        
        $sign = strtoupper(md5($md5str . "key=" . $this->key));
        return $sign;
    }
    
    /**
     * 构造提交表单HTML数据
     * @param $data (请求参数数组)
     * @param $url (网关地址)
     * @return string
     */
    private static function buildForm($data,$url) {
    
        //待请求参数数组
        $sHtml = "<form id='allscoresubmit' name='allscoresubmit' action='".$url."' method='POST'>";
        foreach($data as $key=>$value){
            //            $value = urlencode($value);
            $sHtml.= "<input type='hidden' name='".$key."' value='".$value."'/>";
        }
        //submit按钮控件请不要含有name属性
        $sHtml = $sHtml."<input type='submit' style='display:none;'></form>";
        $sHtml = $sHtml."<script>document.forms['allscoresubmit'].submit();</script>";
        
        return $sHtml;
    }
    
    
    public function server(){
        header('Content-type:text/html;charset=utf-8');
        $ReturnArray = array( // 返回字段
            'memberid' => input('request.memberid'), // 商户ID
            'orderid' =>  input('request.orderid'), // 订单号
            'amount' =>  input('request.amount'), // 交易金额
            'datetime' =>  input('request.datetime'), // 交易时间
            'transaction_id' =>  input('request.transaction_id'), // 支付流水号
            'returncode' => input('request.returncode'),
        );
        $username = input('request.attach');
        $ctime = time();
        $Md5key = 'qxhte4fyfdhhuikoj4v1bpzagvjmhrg7';
        
        ksort($ReturnArray);
        reset($ReturnArray);
        $md5str = '';
        foreach ($ReturnArray as $key => $val) {
            $md5str = $md5str . $key . '=' . $val . '&';
        }
        $sign = strtoupper(md5($md5str . 'key=' . $Md5key));
        if ($sign == input('request.sign') && input('request.returncode') == '00') {
            //更新用户金额、打码量等相关信息
            $order_info = Db::name('chongzhi_list')->where('ddbh',$ReturnArray['orderid'])->find();
            if(sprintf("%.2f",$order_info['je']) != sprintf("%.2f",$ReturnArray['amount'])) return 'error1';
            $user_info = Db::name('username')->where('username',$username)->find();
            $dml_set = Db::name('xt_dmsz')->where('id',1)->find();
            $xtcz = Db::name('xt_chongzhi')->where('id',1)->find();
            if($xtcz['dmopen'] == 1) {
                $dmls = ($order_info['hy_msje'] + $order_info['hy_zsje'] + $order_info['je']+ $order_info['method_money']) * $dml_set['xscz_dmbs'];
            }else{
                $dmls = $order_info['je'] * $dml_set['xscz_dmbs'];
            }
            //充值后账户总金额
            $czhje = $order_info['hy_msje'] + $order_info['hy_zsje'] + $order_info['je'] + $user_info['je']+ $order_info['method_money'];
            //充值总金额
            $czzje = $order_info['je'] + $user_info['czzje'];
            //用户当前打码量
            $dml = $user_info['dml'] + $dmls;
            
            Db::startTrans();
            try {
                $zt = model('ChongzhiList')->where(['ddbh'=>$ReturnArray['orderid']])->value('zt');
                if( 1==intval($zt) ){
                    throw new Exception("该订单已经成功通知");
                }
                if( !model('ChongzhiList')->updateRechargeInfo($ReturnArray['orderid'],$ReturnArray['transaction_id'],1,$czhje,$ctime) ){
                    throw new Exception("更新订单信息错误");
                }
                if( !model('Username')->upUserXsczInfo($czhje,$dml,$czzje,$username) ){
                    throw new Exception("更新用户金额错误");
                }
                Db::name('username')->where('username',$order_info['username'])->setInc('cz_num');
                $fav_money = $order_info['hy_msje']+$order_info['hy_zsje']+ $order_info['method_money'];
                //满送金额，等级赠送金额，充值方案赠送金额
                $extcj = array(
                    'username'=>$user_info['username'],
                    'user_class'=>$user_info['us_class'],
                    'fstime'=>time(),
                    'czadmin' => '系统赠送',
                );
                $cjhje = floatval($order_info['je']) + floatval($user_info['je']) + floatval($order_info['hy_msje']);
                if( floatval($order_info['hy_msje']) > 0 ){
                    $extcj['beizhu'] = '系统赠送，充值满送金额';
                    $extcj['cjje'] = $order_info['hy_msje'];
                    $extcj['cjhje'] = $cjhje;
                    Db::name('caijin_list')->insert($extcj);
                }
                $cjhje += floatval($order_info['hy_zsje']);
                if( floatval($order_info['hy_zsje']) > 0 ){
                    $extcj['beizhu'] = '系统赠送，充值等级赠送金额';
                    $extcj['cjje'] = $order_info['hy_zsje'];
                    $extcj['cjhje'] = $cjhje;
                    Db::name('caijin_list')->insert($extcj);
                }
                $cjhje += floatval($order_info['method_money']);
                if( floatval($order_info['method_money']) > 0 ){
                    $extcj['beizhu'] = '系统赠送，充值方案赠送金额';
                    $extcj['cjje'] = $order_info['method_money'];
                    $extcj['cjhje'] = $cjhje;
                    Db::name('caijin_list')->insert($extcj);
                }
        
                $data = array('username' =>$username,'test'=>"您账户充值金额：{$order_info['je']}，赠送金额：{$fav_money}。已充值到账，请注意查收！",'xx_time'=>$ctime,'ifdq'=>0);
                Db::name('xiaoxi')->data($data)->insert();
                Db::commit();
                return 'ok';
            } catch (\Exception $e) {
                Db::rollback();
                return 'error2';
            }
        }
        return 'error3';
    }
    
    public function page(){
        header('Content-type:text/html;charset=utf-8');
        $ReturnArray = array( // 返回字段
            'memberid' => $_REQUEST['memberid'], // 商户ID
            'orderid' =>  $_REQUEST['orderid'], // 订单号
            'amount' =>  $_REQUEST['amount'], // 交易金额
            'datetime' =>  $_REQUEST['datetime'], // 交易时间
            'transaction_id' =>  $_REQUEST['transaction_id'], // 流水号
            'returncode' => $_REQUEST['returncode']
        );
        
        $Md5key = 'qxhte4fyfdhhuikoj4v1bpzagvjmhrg7';
        
        ksort($ReturnArray);
        reset($ReturnArray);
        $md5str = '';
        foreach ($ReturnArray as $key => $val) {
            $md5str = $md5str . $key . '=' . $val . '&';
        }
        $sign = strtoupper(md5($md5str . 'key=' . $Md5key));
        
        if ($sign == $_REQUEST['sign']) {
            if ($_REQUEST['returncode'] == '00') {
                $this->buildHtml("充值成功，{$ReturnArray['amount']} 元已到账");
            }
        }else{
            $this->buildHtml('充值失败');
        }
    }
}